package sobchak.tools;

import sobchak.event.EventProducer;
import sobchak.ITajik;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 04.03.2010
 * Time: 16:20:08
 * To change this template use File | Settings | File Templates.
 */
public class CementTank extends EventProducer {

	public static final int DEFAULT_TANK_VOLUME = 100;
	public static int tank_count;
	private AtomicInteger exist_volume = new AtomicInteger(DEFAULT_TANK_VOLUME);
	private long buld_time = System.currentTimeMillis();

	private AtomicInteger on_get_enter_count = new AtomicInteger();
	private AtomicInteger on_get_exit_count = new AtomicInteger();

	private volatile boolean is_active;
	private int tank_index = tank_count++;
	private CementBuilder builder;



	CementTank(CementBuilder builder, ITajik tajik) {
		this.builder = builder;
		listener.onEvent(tajik, Events.CEMENT_TANK_NEW);
	}


	void deactivate() {
		is_active = false;
		listener.onEvent(this, Events.CEMENT_TANK_INACTIVE);
	}

	void activate() {
		is_active = true;
		listener.onEvent(this, Events.CEMENT_TANK_ACTIVATED);
	}

	public boolean isActive() {
		return is_active;
	}

	public int getSeqeunce() {
		return tank_index;
	}

	long getBuildTime() {
		return buld_time;
	}

	public int getExistVolume() {
		return exist_volume.get();
	}

	public CementPortion getCementPortion(ITajik tajik) {
		on_get_enter_count.incrementAndGet();
		CementPortion portion = null;
		if(is_active && exist_volume.get() > 0) {
			portion = new CementPortion(tajik);
			builder.cement_used.incrementAndGet();
			exist_volume.decrementAndGet();
		}

		if(on_get_exit_count.incrementAndGet() != on_get_enter_count.get())
			listener.onEvent(tajik, Events.CEMENT_TANK_CONCURRENT_ACCESS);
		return portion;
	}

	
}
